import { getSetting } from './settings';

/**
 * 按键设置接口
 */
export interface KeySettings {
  showBackButton: boolean;
  enableEscapeKey: boolean;
  enableContextMenu: boolean;
  enableKeyboardNavigation: boolean;
}

/**
 * 获取所有按键设置
 * @returns Promise<KeySettings> 按键设置对象
 */
export async function getKeySettings(): Promise<KeySettings> {
  try {
    const [showBackButton, enableEscapeKey, enableContextMenu, enableKeyboardNavigation] = await Promise.all([
      getSetting('show_back_button'),
      getSetting('enable_escape_key'),
      getSetting('enable_context_menu'),
      getSetting('enable_keyboard_navigation')
    ]);

    return {
      showBackButton: showBackButton === 'true', // 明确检查是否为'true'
      enableEscapeKey: enableEscapeKey !== 'false', // 默认为true
      enableContextMenu: enableContextMenu !== 'false', // 默认为true
      enableKeyboardNavigation: enableKeyboardNavigation !== 'false' // 默认为true
    };
  } catch (error) {
    console.error('获取按键设置失败:', error);
    // 返回默认设置
    return {
      showBackButton: true,
      enableEscapeKey: true,
      enableContextMenu: true,
      enableKeyboardNavigation: true
    };
  }
}

/**
 * 设置全局按键处理器
 * @param keySettings 按键设置
 * @param handlers 处理器对象
 * @returns 清理函数
 */
export function setupGlobalKeyHandlers(
  keySettings: KeySettings,
  handlers: {
    onEscape?: () => void;
    onContextMenu?: (e: MouseEvent) => void;
    onKeyDown?: (e: KeyboardEvent) => void;
  }
): () => void {
  const cleanupFunctions: (() => void)[] = [];

  // ESC键处理
  if (keySettings.enableEscapeKey && handlers.onEscape) {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        handlers.onEscape?.();
      }
    };
    window.addEventListener('keydown', handleEscape);
    cleanupFunctions.push(() => window.removeEventListener('keydown', handleEscape));
  }

  // 右键菜单处理
  if (keySettings.enableContextMenu && handlers.onContextMenu) {
    const handleContextMenu = (e: MouseEvent) => {
      e.preventDefault();
      handlers.onContextMenu?.(e);
    };
    window.addEventListener('contextmenu', handleContextMenu);
    cleanupFunctions.push(() => window.removeEventListener('contextmenu', handleContextMenu));
  }

  // 键盘导航处理
  if (keySettings.enableKeyboardNavigation && handlers.onKeyDown) {
    window.addEventListener('keydown', handlers.onKeyDown);
    cleanupFunctions.push(() => window.removeEventListener('keydown', handlers.onKeyDown!));
  }

  // 返回清理函数
  return () => {
    cleanupFunctions.forEach(cleanup => cleanup());
  };
}

/**
 * 检查是否应该显示返回按钮
 * @returns Promise<boolean>
 */
export async function shouldShowBackButton(): Promise<boolean> {
  try {
    const setting = await getSetting('show_back_button');
    return setting === 'true'; // 明确检查是否为'true'
  } catch (error) {
    console.error('获取返回按钮设置失败:', error);
    return true; // 默认显示
  }
}